//
//  SetViewController.m
//  dhfsAPP
//
//  Created by Devil on 2017/8/2.
//  Copyright © 2017年 Devil. All rights reserved.
//

#import "SetViewController.h"
#import "fsapp-Swift.h"
@interface SetViewController ()

@property(strong,nonatomic)SetView *setView;

@end

@implementation SetViewController
#pragma mark - 懒加载
-(SetView *)setView{
    if (!_setView) {
        _setView = [[SetView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        
        _setView.headerView.headerViewDelegate = self;
        
        _setView.setViewDelegate = self;
    }
    
    return _setView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    
    [self.view addSubview:self.setView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - HeaderViewDelegate实现
-(void)clickHeaderViewBtn{
    [self.navigationController popViewControllerAnimated:true];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - SetViewDelegate实现
-(void)logout{
    LoginViewController *vc = [[LoginViewController alloc] init];
    
    [vc clearUsd];
    NSURL *myurl = [NSURL URLWithString:@"http://dahan-api.heiyou.net/index.php/home/user/login"];
    if (myurl) {
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:myurl];
        //cookies  获得该域名下 cookie 的信息
        for (int i = 0; i < [cookies count]; i++) {
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];// 删除所有cookie
        }
    }
    
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)deleteCollect{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要清空收藏？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancelCollect];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)deleteCache{
    [SVProgressHUD showWithStatus:@"计算中缓存中"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
        
        unsigned long long size = [self folderSizeAtPath:cachePath];
        
        size += [SDImageCache sharedImageCache].getSize;   //CustomFile + SDWebImage 缓存
        
        //设置文件大小格式
        NSString *sizeText = nil;
        if (size >= pow(10, 9)) {
            sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
        }else if (size >= pow(10, 6)) {
            sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
        }else if (size >= pow(10, 3)) {
            sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
        }else {
            sizeText = [NSString stringWithFormat:@"%zdB", size];
        }
        
        [SVProgressHUD dismiss];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%@,确定全部删除？",sizeText] preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self cancelCollect];
            [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                [SVProgressHUD showSuccessWithStatus:@"清除成功"];
            }];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
        
        [self presentViewController:alert animated:YES completion:nil];
    });
}

-(void)pushVC:(UINavigationController *)vc{
    [self presentViewController:vc animated:YES completion:nil];
    //[self.navigationController pushViewController: vc animated:true];
}

#pragma mark - 禁止屏幕旋转
-(BOOL)shouldAutorotate{
    return NO;
}

#pragma mark - 获取缓存大小
// 遍历文件夹获得文件夹大小，返回多少 M
- ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
    }
    
    return folderSize/( 1024.0 * 1024.0);
    
}



// 计算 单个文件的大小
- ( long long ) fileSizeAtPath:( NSString *) filePath{
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
}

#pragma 清理缓存图片


#pragma mark - 其它函数
-(void)cancelCollect{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    //    NSDictionary *parameters = @{@"page":@"1",@"client_type":@"1"};
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/clearCollection" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 200)
         {
             UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"清除成功" preferredStyle:UIAlertControllerStyleAlert];
             
             [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil]];
             
             [self presentViewController:alert animated:YES completion:nil];
         }
         else if ([responseObject[@"status"] integerValue] == 1018)
         {
             [SVProgressHUD showErrorWithStatus:@"清除失败，您没有添加任何收藏"];
         }
         else if([responseObject[@"status"] integerValue] == 199)
         {
             UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未登录，无法找到您的收藏" preferredStyle:UIAlertControllerStyleAlert];
             
             [alert addAction:[UIAlertAction actionWithTitle:@"暂不登录" style:UIAlertActionStyleDefault handler:nil]];
             [alert addAction:[UIAlertAction actionWithTitle:@"前往登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                 
             }]];
             
             [self presentViewController:alert animated:YES completion:nil];
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"失败");
     }];
}
@end
